package com.peng.handler;

import com.alibaba.fastjson.JSON;
import com.peng.dao.pojo.SysUser;
import com.peng.service.LoginService;
import com.peng.utils.UserThreadLocal;
import com.peng.vo.ErrorCode;
import com.peng.vo.Result;
import com.qiniu.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginHandler implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 1 判断是否是controller的方法 ，访问静态资源放行
         * 2 判断是否登录
         * 3 根据token验证是否登录
         * 4 如果不为空，直接放行
         */

        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("Authorization");
        System.out.println(token);
        if (token==null){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(),ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        SysUser userByToken = loginService.findUserByToken(token);
        if (userByToken==null){
            Result result = Result.fail(ErrorCode.LOGINOUT_ERROR.getCode(),ErrorCode.LOGINOUT_ERROR.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        UserThreadLocal.set(userByToken);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //如果不删除可能会出现内存溢出
        UserThreadLocal.remove();
    }
}
